<?php
/**
 * Created by Zhy
 * User: Zhy
 * Date: 2018/8/28
 * Time: 11:10
 */

namespace app\api\controller;

use think\Db;

class Ali extends Base
{
    protected $config = array(
        'partner' => '2088621781822784',//用不着
        'seller_id' => 'admin@bagepanzi.com',//用不着
        'sign_type' => 'RSA2',// 直接写死了
        'it_b_pay' => '10m',//用不着
        'md5' => 'djqm7budkdlki6a76yasuyb9s1riiu1j',//用不着
        'ali_public' => 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAnM8TA9p3CmsjvYQmHViw6n7QPnlp0SwUkJNgPGRW6O96YugUDtNUuEmG6pDvwNchMRXKTdCig8/UgiWK55Vej7aXf/VS9H1H2LMDB4wAZm768xss+NQdbiQGF/kMkqJT0AUlhjc/+jF5E6oRO62Z/j7zL1qyxCxAb2zq8nnZ6KTqGSAnRKelWMaxBmEKYQCkzS0/aAT6/mfoK1jwS9N1S1OqUADVQqFcOC98go3zIhiayAdAYDGW/Wd3GnHay2xqnFEx0lMV1WB6dhS6rSFnlhBDhofvI1icz85A4e82pL0IZjOQOSRWW9OSJgbkQ7War7RbPAm9MBWbCcnM/uVckwIDAQAB',
        'public_key' => "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAq4j37rEeEbCxMV+xHLf3lZBPfnVsIjDtVs9mkbsdcDAB11ROCikpxAKIgn2mzlraOhltzVBPI79ghbGCYNlm5Jr9vtoyu2u7pHh/GlkHQZllT0ZMNaBhhx5c8l4Kyb/abtIkh7qQtsT7SefifjZRp4te8NcId+CIsWrie4+WszdToBbSl7tJsG8K6pQv3p7/E8ypWbTHPNXIlCJjfKd29mmutHJBHGjERLaCGj5Jn7h/4rvJrARiQTOgnwP8VDJUbJj2/GstDoGgyBgPMe/eGzcvf36uxOVIEikDIICQFMkwWR1/a1RzyXcK3TOutMuGrEFYOEXwQrR9BVr4RIMyYwIDAQAB",
        'private_key' => 'MIIEowIBAAKCAQEAq4j37rEeEbCxMV+xH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rju3kBqLdTUXfSQP9yGMarQDpfllARUMXtwqNzL2KthQMa77ecuErvrST7mwurbexHfrSBj52IZgWO+LbaTx3SKhhpzk8V1a3bVyJvDj6NGA7AW8dXCY+qR8bEWEI05JoPRQKBgCo3JOvvwlfw7Jd1JrRCzVKsazP7m0K8G4tfagH47K59VChr9+aMh0ALmDb8ibcP+rOErf4W6JtZDIlu2BbcAkdxBOMxDPVhUtGz1HPRdoEH9de1VuHfbiY5RPAIHg/LLS/Zsg3a6fXaknF4EBf5INAHhr15so7U/lYYUbOoYoHfAoGBAMkg7svBwNGz+OMiRGCcwUtuI66nw+MwhYkSXQrWHd0CarMkqkQV9hdiTHgwTiR86eJcCAgItEa+Py+2oSJE3K7SBCUlAZnmELGzXnDf15PJ+mT6S7LtCNoks9/2YbP3j2MjKmhXgaOG6YHxjxZ+UARlV4mVk+qZbPNsYQxJ1gAR'
    );
    public $body;//描述
    public $subject;//描述
    public $total_amount;//金额
    public $out_trade_no;//订单号
    /**
     * 异地登录验证
     * @return string
     */
    public function __construct()
    {
        $useridddd = input('user_id');
        $time = input('time');
        $value = input('value');
        $reqKey = input('reqKey');
        $auth = $this->checkAll($useridddd,$time,$value,$reqKey);
        if($auth == 112){
            echo json_encode(['status'=>301,'msg'=>$this->otherLogin]);
            exit;
        }elseif($auth == 110){
            echo json_encode(['status' => 302, 'msg' => $this->frost]);
            exit;
        }elseif($auth == 2111){
            echo json_encode(['status' => 303, 'msg' => $this->del]);
            exit;
        }
    }
    /**
     * @param $no
     * @param $money
     * @return string
     * 支付宝支付
     */
    public function getParam($no, $money, $body, $subject)
    {
//
        import('alipay.aop.AopClient', EXTEND_PATH);
        import('alipay.aop.request.AlipayTradeAppPayRequest', EXTEND_PATH);

        try {
            $aop = new \AopClient;
            $aop->gatewayUrl = "https://openapi.alipay.com/gateway.do?charset=utf-8";
            $aop->appId = "2021001162653764";
            $aop->rsaPrivateKey = $this->config['private_key'];
            $aop->format = "json";
            $aop->charset = "UTF-8";
            $aop->signType = "RSA2";
            $aop->alipayrsaPublicKey = $this->config['public_key'];
            $request = new \AlipayTradeAppPayRequest();
            $bizcontent = "{\"body\":\"" . $body . "\","
                . "\"subject\": \"" . $subject . "\","
                . "\"out_trade_no\": \"" . $no . "\","
                . "\"timeout_express\": \"30m\","
                . "\"total_amount\": \"" . $money . "\","
                . "\"product_code\":\"QUICK_MSECURITY_PAY\""
                . "}";
            $request->setNotifyUrl("http://test.xuanwumobile.com/api/Ali/huidiao");
            $request->setBizContent($bizcontent);
            $response = $aop->sdkExecute($request);
//            return $response;
            $res['msgsss'] = $response;
            $res['status'] = 200;
            return $res;
//            return json_encode($res);
        } catch(\Exception $e) {
            $res['msgsss'] = 'error';
            $res['status'] = 0;
            return $res;
        }
    }
    
    /**
     * 验证返回
     * @return bool
     */
    public function checkReturn()
    {
        import('alipay.aop.AopClient', EXTEND_PATH);
        $aop = new \AopClient;
        $aop->alipayrsaPublicKey = $this->config['ali_public'];
        $flag = $aop->rsaCheckV1($_POST, NULL, "RSA2");
        if($flag) {
            return $_POST;
        } else {
            return false;
        }
    }
    /***
     * @param $code
     * @param string $msg
     * 错误返回信息
     */
    protected function apiError($code, $msg = '')
    {
        if (!$msg) {
            $info['msg'] = $this->_error[$code]['msg'];
        } else {
            $info['msg'] = $msg;
        }
        $info['status'] = $code;
        $returnInfo = json_encode($info, JSON_UNESCAPED_UNICODE);
        echo $returnInfo;
        exit();
    }
    /**
     * 生成订单
     * @return
     * order_id    订单ID
     */
    public function alipay()
    {
        $order_id = input('order_id');
        $order = Db::table('up_order')
            ->field('order_num, order_price, order_cate')
            ->where('order_id', $order_id)
            ->find();
        if($order['order_cate'] == 1 || $order['order_cate'] == 2){
            $this->body = '赛事照片购买';
            $this->subject = '赛事照片购买费用';
        }elseif($order['order_cate'] == 3 || $order['order_cate'] == 4){
            $this->body = '赛事报名';
            $this->subject = '赛事报名费用';
        }else{
            $this->body = '图书购买';
            $this->subject = '图书购买费用';
        }
        
        $this->total_amount =$order['order_price'];
//        $this->total_amount =0.01;
        $this->out_trade_no = $order['order_num'];
        $respont = $this->getParam($this->out_trade_no, $this->total_amount, $this->body, $this->subject);
        return json_encode($respont);
    }
    
    /**
     * 回调
     * @return string
     */
    public function write_admin_log($data)
    {
        $file_name = 'file/log/' . date('Ymd', time()) . '.txt';
        if (is_array($data)) {
            $data_str = implode(' | ', $data);
        } else {
            $data_str = $data;
        }
        file_put_contents($file_name, $data_str . "\r\n\r\n", FILE_APPEND);
    }
    
    /**
     * 回调
     * @return string
     */
    public function huidiao()
    {
        $getInfo = $this->checkReturn();
        if($getInfo) {
            if($getInfo['trade_status'] == 'TRADE_SUCCESS' || $getInfo['trade_status'] == 'TRADE_FINISHED') {
                $num = $getInfo['out_trade_no']; //订单号
                $order = Db::table('up_order')
                    ->where('order_num', $num)
                    ->field('order_user_id, order_id, order_cate, order_match_id, order_status, 
                    order_type, order_image_id')
                    ->find();
                $match = Db::table('up_match')
                    ->where('match_id', $order['order_match_id'])
                    ->field('match_cate')
                    ->find();
                
                if($order['order_status'] == 1){
                    Db::startTrans();
                    try{
                        if($order['order_cate'] == 3 || $order['order_cate'] == 4){ // 赛事
                            // 修改报名信息状态
                            Db::table('up_match_apply_info')
                                ->where('ma_order_num', $num)
                                ->setField('ma_apply_status', 2);
                            
                            // 修改赛事报名人数  up_match_apply_group
                            if($match['match_cate'] == 1){ // 帆船
                                $apply = Db::table('up_match_apply_info')
                                    ->where('ma_user_id', $order['order_user_id'])
                                    ->where('ma_match_id', $order['order_match_id'])
                                    ->field('ma_group')
                                    ->find();
                                Db::table('up_match_apply_group')
                                    ->where('mag_match_id', $order['order_match_id'])
                                    ->where('mag_group_id', $apply['ma_group'])
                                    ->setInc('mag_already_num');
                            }else{
                                // 按组别分组
                                $apply = Db::table('up_match_apply_info')
                                    ->field('count(ma_group) group_num, ma_group')
                                    ->where('ma_role', 1)
                                    ->where('ma_order_num', $num)
                                    ->group('ma_group')
                                    ->select();
                                foreach($apply as $kk => $vv){
                                    Db::table('up_match_apply_group')
                                        ->where('mag_match_id', $order['order_match_id'])
                                        ->where('mag_group_id', $vv['ma_group'])
                                        ->setInc('mag_already_num', $vv['group_num']);
                                }
                            }
                        }elseif($order['order_cate'] == 1 || $order['order_cate'] == 2){ // 照片
                            // 插入我购买的照片  up_my_pay_images
                            $images = [];
                            $img = explode(',', $order['order_image_id']);
                            foreach($img as $k => $v){
                                $images[$k] = [
                                    'mpi_user_id' => $order['order_user_id'],
                                    'mpi_image_id' => $v
                                ];
                            }
                            Db::table('up_my_pay_images')->insertAll($images);
                        }else{ // 图书
                            
                        }
                        
                        // 修改订单信息
                        Db::table('up_order')
                            ->where('order_id', $order['order_id'])
                            ->update([
                                'order_status' => 2,
                                'order_pay_time' => date('Y-m-d H:i:s')
                            ]);
                        
                        // 代付需要发送系统消息
                        if($order['order_type'] == 4){
                            $notice = [
                                'notice_title' => '支付通知',
                                'notice_content' => '您发送的代付订单“' . $num . '”已经被支付成功。',
                                'notice_range' => 2,
                                'notice_user' => ',0,' . $order['order_user_id'] . ',',
                                'notice_read_user' => ',0,',
                                'notice_del_user' => ',0,',
                                'notice_type' => 2,
                                'notice_committee_id' => 0,
                                'notice_time' => date('Y-m-d H:i:s')
                            ];
                            Db::table('up_notice')->insert($notice);
                        }
                        Db::commit();
                        return 'success';
                    }catch(\Exception $e){
                        Db::rollback();//回滚
                        return 'error';
                    }
                }else{
                    return 'success';
                }
                
            }
        }
    }


    /**
     *支付宝的原路退款接口(商户处理用户的订单)
     */
    public function refund(){
        $payInfo = array();
        $payInfo['number'] = '201905311701374074';
        $payInfo['money'] = 12;
        //仨参数：money,number
        import('alipay.aop.AopClient',EXTEND_PATH);
        import('alipay.aop.request.AlipayTradeRefundRequest',EXTEND_PATH);
        $aop = new \AopClient;
        $aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';
        $aop->appId = '2019080566158002';
        $aop->rsaPrivateKey = $this->config['private_key'];
        $aop->alipayrsaPublicKey=$this->config['public_key']; //不应该用这个，用ali_public
        $aop->apiVersion = '1.0';
        $aop->signType = 'RSA2';
        $aop->postCharset='UTF-8';
        $aop->format='json';
        $request = new \AlipayTradeRefundRequest;
        $refundAmount = $payInfo['money'];
        $request->setBizContent("{" .
            "\"out_trade_no\":\"".$payInfo['number']."\"," .
            "\"trade_no\":\"\"," .
            "\"refund_amount\":".$refundAmount."," .
            "\"refund_reason\":\"退款\"" .
            "  }");
        $result = $aop->execute($request);
        $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
        $resultCode = $result->$responseNode->code;
        if(!empty($resultCode) && $resultCode == 10000){
            return array('status'=>200,'msg'=>'操作成功');
        }else{
            return array('status'=>0,'msg'=>'调用接口失败');
        }
    }
}